from datetime import timedelta
from typing import Annotated
import random
import string
from fastapi import APIRouter, Depends, status, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from app.api.deps import CurrentUser, SessionDep
from app.core import security
from app.core.config import settings
from app.core.security import get_password_hash
from app.models import  Token, LoginForm,TokenResponse,UserPublicResponse,PhoneRegisterRequest,PhoneRegisterResponse,PhoneVerificationCodeRequest,PhoneVerificationCodeResponse,UserAuth,CaptchaResponse
from app.core.security import verify_password
from app import services
from app import  models

router = APIRouter()
# 获得用户详情
@router.get("/users/me", response_model=models.UserMeResponse)
async def user_me(current_user: CurrentUser):
    
    return models.UserMeResponse(
        code=0,
        data=current_user,
        message="获取用户信息成功"
    )
    
# # 手机号注册
# @router.post("/token/phoneregister", response_model=PhoneRegisterResponse)
# async def register_user_by_phone(request: PhoneRegisterRequest,session: SessionDep):
#      return await services.UsersService(db=session,current_user=None).register_user_by_phone(request)

# @router.post("/login/access-token")
# async def login_access_token(
#     session: SessionDep, form_data: models.LoginForm
# ) -> models.LoginResultResponse:
#     """
#     OAuth2 compatible token login, get an access token for future requests
#     """
    
#     fileter_str={}
#     fileter_str['account']=form_data.username 
#     if form_data.login_type=='PHONE':    
#         fileter_str['accountType']=models.AccountType.PHONE    
#     elif form_data.login_type=='EMAIL':
#         fileter_str['accountType']=models.AccountType.EMAIL
#     else:
#         pass
#     db_user = await services.UsersService(db=session,current_user=None).find_user_with_auth_by(fileter_str)     
    
#     if not db_user:
#         return models.LoginResultResponse(code=400, msg="不正确的用户名",data=None)        
#     if not verify_password(form_data.password, db_user.hashed_password):
#         return models.LoginResultResponse(code=400, msg="不正确的密码",data=None)                

#     access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
#     token = security.create_access_token(
#                 subject={"userId":db_user.id, 
#                  "account":db_user.account,
#                  "accountType":db_user.accountType
#               },expires_delta=access_token_expires
#             )
#     user_dict = db_user.dict()
#     # if hasattr(db_user, 'userauths') and db_user.userauths:
#     #     approved_auths = [auth.dict() for auth in db_user.userauths if auth.authStatus == models.AuthStatusEnum.APPROVED]
#     #     user_dict['auth_info'] = approved_auths
#     # else:
#     #     user_dict['auth_info'] = []
        
#     return models.LoginResultResponse(code=0, msg="登录成功",data={**user_dict,"token":token})  
        
   
    

    


@router.post("/auth/login")
def login(request: LoginForm) -> models.LoginResultResponse:
    """
    登录
    """
    if request.username in ("admin",'editor') and request.password in ("12345678"):        
        access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        token = security.create_access_token(
                subject={"userId":request.username               
              },expires_delta=access_token_expires
            )
        
        return models.LoginResultResponse(code=0,message="成功",data={"token":token})
    return models.LoginResultResponse(code=400, message="不正确的用户名或密码",data=None)    


@router.get("/auth/captcha", response_model=CaptchaResponse)
def get_captcha() -> CaptchaResponse:
    """
    获得验证码
    """
    # 生成4位随机验证码（数字和字母组合）
    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
    
    return CaptchaResponse(
        code=0,
        data=f"http://dummyimage.com/100x40/dcdfe6/000000.png&text={captcha_text}",
        message="获取验证码成功"
    )
    

# @router.post("/password-recovery/{email}")
# def recover_password(email: str, session: SessionDep) -> Message:
#     """
#     Password Recovery
#     """
#     pass
#     # user = crud111.get_user_by_email(session=session, email=email)

#     # if not user:
#     #     raise HTTPException(
#     #         status_code=404,
#     #         detail="The user with this email does not exist in the system.",
#     #     )
#     # password_reset_token = generate_password_reset_token(email=email)
#     # email_data = generate_reset_password_email(
#     #     email_to=user.email, email=email, token=password_reset_token
#     # )
#     # send_email(
#     #     email_to=user.email,
#     #     subject=email_data.subject,
#     #     html_content=email_data.html_content,
#     # )
#     # return Message(message="Password recovery email sent")


# @router.post("/reset-password/")
# def reset_password(session: SessionDep, body: NewPassword) -> Message:
#     """
#     Reset password
#     """
#     pass
#     # user_id = verify_password_reset_token(token=body.token)
#     # if not user_id:
#     #     raise HTTPException(status_code=400, detail="Invalid token")
#     # user = crud111.get_user_by_email(session=session, email=email)
#     # if not user:
#     #     raise HTTPException(
#     #         status_code=404,
#     #         detail="The user with this email does not exist in the system.",
#     #     )
#     # elif not user.is_active:
#     #     raise HTTPException(status_code=400, detail="Inactive user")
#     # hashed_password = get_password_hash(password=body.new_password)
#     # user.hashed_password = hashed_password
#     # session.add(user)
#     # session.commit()
#     # return Message(message="Password updated successfully")


# @router.post(
#     "/password-recovery-html-content/{email}",
#     dependencies=[Depends(get_current_active_superuser)],
#     response_class=HTMLResponse,
# )
# def recover_password_html_content(email: str, session: SessionDep) -> Any:
#     """
#     HTML Content for Password Recovery
#     """
#     user = crud111.get_user_by_email(session=session, email=email)

#     if not user:
#         raise HTTPException(
#             status_code=404,
#             detail="The user with this username does not exist in the system.",
#         )
#     password_reset_token = generate_password_reset_token(email=email)
#     email_data = generate_reset_password_email(
#         email_to=user.email, email=email, token=password_reset_token
#     )

#     return HTMLResponse(
#         content=email_data.html_content, headers={"subject:": email_data.subject}
#     )
